<template>
	<custom-nav :showBackArrow="true" :title="'设备配置'"></custom-nav>
	<view class="page-setting" :style="pagePaddingTop"  > 
		<view class="device_wrap" >
			<view class="device_left" > 
				<image src="/static/bluetooth/bluetooth_connect.png" mode="aspectFill" class="connect_icon" v-if="isConnect" />
				<image src="/static/bluetooth/connect.png" mode="aspectFill" class="connect_icon" v-else />
				<view class="device_info" >
					<view class="device_title" >{{ params.localName || params.name }}</view>
					<view class="device_desc" >{{ params.deviceId }}</view>
					<view class="device_desc" >设备型号：{{params.name}}</view>
				</view>
			</view>
			
			<view class="un_connect" :class="{ 'connect_text': isConnect }" >{{ !isConnect ? '未连接' : '已连接' }}</view>
		</view>
		
		<view class="connect_btn" @click="handleConnect" v-if="!isConnect && !loading" >
			<image src="/static/bluetooth/connect_btn.png" mode="aspectFill" class="connect_btn_icon" />
			连接
		</view>
		
		<view class="un_connect_btn" v-if="isConnect && !loading" @click="disconnectBluetooth" >
			<image src="/static/bluetooth/un_connect.png" mode="aspectFill" class="connect_btn_icon" />
			断开连接
		</view>
		
		<view class="connect_btn" v-if="loading" >
			<image src="/static/bluetooth/connecting.png" mode="aspectFill" class="connect_btn_icon" />
			连接中...
		</view>
	</view>
</template>

<script setup >
import {
	ref,
	computed,
	onMounted,
	getCurrentInstance
} from "vue"

const userStore = useUser();
import {
	useUser
} from "@/hooks/useUser.js"
// 用户信息
let userInfo = ref(null)

import Base64 from "@/libs/js-base64/index.js"
const showBluetooth = ref(false)
const loading = ref(false)
let params = ref('')
const list = ref([])
import CustomNav from "@/components/custom-nav/index.vue"
import {
	getNavHeightTop
} from "@/stores/navStore.js"
const isConnect = ref(false)
import { insertBluetooth, getConnectDevices } from '@/http/apis/bluetoothAPI.js'


let navHeightInfo = getNavHeightTop();
const pagePaddingTop = ref({
	"paddingTop": (navHeightInfo.navTotalHeight + uni.upx2px(24)) + 'px'
})

const disconnectBluetooth = () => {
	console.log('断开连接')
	const { deviceId } = params.value
	uni.showModal({
		title: '提示',
		content: '是否断开连接？',
		success(res) {
			if(res.confirm) {
				uni.closeBLEConnection({
					deviceId,
					success(res) {
						uni.showToast({
							title: '蓝牙已断开',
							icon: 'none',
							duration: 2000
						})
						isConnect.value = false
					},
					fail(res) {
						uni.showToast({
							title: '操作失败',
							icon: 'none',
							duration: 2000
						})
					}
				})
			}
		}
	})
}

const createBLEConnection = deviceId => {
	const { localName, name } = params.value
	const { id_public_user_info } = userInfo.value
	console.log('id_public_user_info:', id_public_user_info)
	loading.value = true
	uni.createBLEConnection({
		deviceId,
		async success(res) {
			loading.value = false
			isConnect.value = true
			// 判断之前是否连接过 ...
			if(!isConnectFlag()) {
				console.log('进来了...')
				const result = await insertBluetooth({
					id_public_user_info,
					invoke_method: 'public_insert_or_update_middle_table',
					pre_db_para_middle_table_name: 'public_middle_table_lite_mod_bluetooth',
					type_middle_app: '23001',
					type_inner_app: '10001',
					is_online: '0',
					pre_db_para_begin_idx: '0',
					pre_db_para_length_4_list: '10',
					mid_table_remark_001: Base64.encode(name || localName),
					mid_table_remark_002: Base64.encode(deviceId),
					mid_table_remark_003: '',
					mid_table_remark_004: '401',
					mid_table_remark_040: new Date().getTime()
				})
			}
		},
		fail(res) {
			console.log('失败：', res)
			loading.value = false
			uni.showToast({
				title: '连接失败',
				icon: 'none',
				duration: 2000
			})
		}
	})
}

/**
 * 连接方法
 * */
const handleConnect = () => {
	const { deviceId } = params.value
	createBLEConnection(deviceId)
}

const getList = () => {
	userStore.getUserInfo().then(async res => {
		userInfo.value = res?.public_user_info || {};
		console.log('res:', res)
		const { id_public_user_info } = userInfo.value
		const result = await getConnectDevices({
			invoke_method: 'public_load_middle_table_list',
			pre_db_para_middle_table_name: 'public_middle_table_lite_mod_bluetooth',
			type_middle_app: '23001',
			type_inner_app: '10001',
			is_online: '0',
			pre_db_para_begin_idx: '0',
			pre_db_para_length_4_list: '10',
			id_public_user_info
		})
		list.value = result.page_content
		list.value.map(item => {
			item.mid_table_remark_002 = Base64.decode(item.mid_table_remark_002)
			item.mid_table_remark_001 = Base64.decode(item.mid_table_remark_001)
		})
	}, err => {
		console.log(err, '>>>userinfo')
	})
	
	
}

const isConnectFlag = () => {
	const { deviceId } = params.value
	let index = list.value.findIndex(item => { return item.mid_table_remark_002 == deviceId })
	return index > -1
}


/**
 * 获取已连接的设备
 * */
const getConnectedBluetoothDevices = () => {
	uni.getConnectedBluetoothDevices({
		success(res) {
			let devices = res.devices
			let index = devices.findIndex(item => { return item.deviceId == params.value.deviceId })
			if(index > -1) {
				isConnect.value = true
			}
		},
		fail(res) {
			console.log('fail:', res)
		}
	})
}

onMounted(event => {
	let options = getCurrentInstance()
	const { deviceInfo } = options.attrs.__pageInstance.options
	params.value = JSON.parse(deviceInfo)
	getList()
	// 获取已连接设备 
	getConnectedBluetoothDevices()
})


</script>

<style scoped lang="less" >
.page-setting {
	position: relative;
	width: 100%;
	min-height: 100vh;
	background-color: #182836;
	font-size: 30rpx;
	// font-family: PingFang SC;
	font-weight: 500;
	color: #FFFFFF;
	line-height: 30rpx;
	box-sizing: border-box;
	padding: 24rpx 32rpx;
	
	image {
		display: block;
	}
	
	.device_wrap {
		box-sizing: border-box;
		padding: 42rpx 32rpx;
		background-color: #2D4052;
		border-radius: 28rpx;
		display: flex;
		position: relative;
	}
	
	.device_left {
		display: flex;
		align-items: flex-start;
	}
	
	.connect_icon {
		width: 120rpx;
		height: 120rpx;
		margin: 0 30rpx 0 0;
	}
	
	.device_info {
		width: 368rpx;
		white-space: pre-wrap;
		color: #fff;
	}
	
	.device_title {
		font-size: 34rpx;
		font-weight: 600;
		line-height: 40rpx;
	}
	
	.device_desc {
		font-size: 24rpx;
		color: rgba(255, 255, 255, .5);
		margin: 5rpx 0 0 0;
	}
	
	.un_connect {
		position: absolute;
		top: 52rpx;
		right: 32rpx;
		color: rgba(255, 255, 255, .5);
		font-size: 22rpx;
	}
	
	.connect_text {
		color: #00FFF6;
	}
	
	.connect_btn {
		position: fixed;
		left: 0;
		right: 0;
		margin: 0 auto;
		bottom: 84rpx;
		width: 402rpx;
		height: 88rpx;
		background: linear-gradient(180deg, #00FFF6 0%, #28C0FF 100%);
		border-radius: 44rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		color: #182836;
		font-size: 34rpx;
		font-weight: bold;
	}
	
	.connect_btn_icon {
		width: 48rpx;
		height: 48rpx;
		margin: 0 16rpx 0 0;
	}
	
	.un_connect_btn {
		position: fixed;
		left: 0;
		right: 0;
		margin: 0 auto;
		bottom: 84rpx;
		width: 402rpx;
		height: 88rpx;
		border: 2rpx solid #00FFF6;
		color: #00FFF6;
		border-radius: 44rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: 34rpx;
		font-weight: bold;
	}
}
</style>